﻿using System;
using System.Collections.Generic;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using WeMakeSP.Platform.SharePoint.Controls;
using WeMakeSP.WebComponents.RSSAdvancedReaderWebPart;

namespace WeMakeSP.WebComponents.RSSAdvancedReaderWebPart
{
    /// <summary>
    /// The RSS advanced reader user control.
    /// </summary>
    public partial class RSSAdvancedReader : UserControlBase, IRSSAdvancedReaderView
    {
        #region Fields

        /// <summary>
        /// The RSS advanced reader presenter.
        /// </summary>
        private IRSSAdvancedReaderPresenter presenter;

        #endregion

        #region Constructors

        /// <summary>
        /// Initializes a new instance of the <see cref="RSSAdvancedReader"/> class.
        /// </summary>
        public RSSAdvancedReader()
        {
            // Initialize the instance.

            this.Initialize();
        }

        #endregion

        #region Public Events

        /// <summary>
        /// Occurs when [feed item body displaying].
        /// </summary>
        public event FeedItemRefresh FeedItemBodyDisplaying;

        /// <summary>
        /// Occurs when [feed refreshing].
        /// </summary>
        public event FeedRefresh FeedRefreshing;

        /// <summary>
        /// Occurs when [feed showing all].
        /// </summary>
        public event FeedRefresh FeedShowingAll;

        #endregion

        #region Public Properties

        /// <summary>
        /// Gets or sets a value indicating whether [asynchronous load].
        /// </summary>
        /// <value><c>True</c> if [asynchronous load]; otherwise, <c>false</c>.</value>
        public bool AsynchronousLoad
        {
            get;
            set;
        }

        /// <summary>
        /// Gets or sets the auto refresh interval.
        /// </summary>
        /// <value>The auto refresh interval.</value>
        public int AutoRefreshInterval
        {
            get;
            set;
        }

        /// <summary>
        /// Gets or sets the data source.
        /// </summary>
        /// <value>The data source.</value>
        public object DataSource
        {
            get
            {
                return this.GetFeedsContainer().DataSource;
            }

            set
            {
                this.GetFeedsContainer().DataSource = value;
            }
        }

        /// <summary>
        /// Gets or sets the height of the feed image max.
        /// </summary>
        /// <value>The height of the feed image max.</value>
        public int FeedImageMaxHeight
        {
            get;
            set;
        }

        /// <summary>
        /// Gets or sets the width of the feed image max.
        /// </summary>
        /// <value>The width of the feed image max.</value>
        public int FeedImageMaxWidth
        {
            get;
            set;
        }

        /// <summary>
        /// Gets or sets the feeds.
        /// </summary>
        /// <value>The feeds.</value>
        public string Feeds
        {
            get;
            set;
        }

        /// <summary>
        /// Gets or sets the item view.
        /// </summary>
        /// <value>The item view.</value>
        public RSSAdvancedReaderItemView ItemView
        {
            get;
            set;
        }

        /// <summary>
        /// Gets a value indicating whether this instance is in async post back.
        /// </summary>
        /// <value>
        /// <c>True</c> if this instance is in async post back; otherwise, <c>false</c>.
        /// </value>
        public bool IsInAsyncPostBack
        {
            get
            {
                return
                    ScriptManager.GetCurrent(this.Page).IsInAsyncPostBack;
            }
        }

        /// <summary>
        /// Gets or sets the limit.
        /// </summary>
        /// <value>The limit.</value>
        public int Limit
        {
            get;
            set;
        }

        /// <summary>
        /// Gets or sets the orientation.
        /// </summary>
        /// <value>The orientation.</value>
        public RSSAdvancedReaderOrientation Orientation
        {
            get;
            set;
        }

        /// <summary>
        /// Gets or sets a value indicating whether [show feed image].
        /// </summary>
        /// <value><c>True</c> if [show feed image]; otherwise, <c>false</c>.</value>
        public bool ShowFeedImage
        {
            get;
            set;
        }

        /// <summary>
        /// Gets or sets a value indicating whether [show publication date].
        /// </summary>
        /// <value><c>true</c> if [show publication date]; otherwise, <c>false</c>.</value>
        public bool ShowPublicationDate
        {
            get;
            set;
        }

        #endregion

        #region Protected Methods

        /// <summary>
        /// Handles the Load event of the Page control.
        /// </summary>
        /// <param name="sender">The source of the event.</param>
        /// <param name="e">The <see cref="System.EventArgs"/> instance containing the event data.</param>
        protected void Page_Load(object sender, EventArgs e)
        {
        }

        /// <summary>
        /// Asynchronouses the load event handler.
        /// </summary>
        /// <param name="sender">The sender.</param>
        /// <param name="e">The <see cref="System.EventArgs"/> instance containing the event data.</param>
        protected void AsynchronousLoadEventHandler(object sender, EventArgs e)
        {
            // Diplay the data view.

            this.MainLayoutMultiView.ActiveViewIndex = 1;

            // Disable the timer.

            this.AsynchronousLoadTimer.Enabled = false;
        }

        /// <summary>
        /// Feeds the item show body click event handler.
        /// </summary>
        /// <param name="sender">The sender.</param>
        /// <param name="e">The <see cref="System.EventArgs"/> instance containing the event data.</param>
        protected void FeedItemShowBodyClickEventHandler(object sender, EventArgs e)
        {
            ImageButton feedItemShowBodyButton = sender as ImageButton;

            if (feedItemShowBodyButton != null)
            {
                if (this.FeedItemBodyDisplaying != null)
                {
                    string[] commandArguments =
                       feedItemShowBodyButton.CommandArgument.Split(';');

                    // Check if the command argument is valid.

                    if (commandArguments.Length == 3)
                    {
                        string feedUrl = commandArguments[0];
                        string feedItem = commandArguments[1];

                        int itemCount = 0;
                        int.TryParse(commandArguments[2], out itemCount);

                        this.FeedItemBodyDisplaying(sender, new FeedItemRefreshEventArgs(feedUrl, feedItem, itemCount));
                    }
                }
            }
        }

        /// <summary>
        /// Feedses the refresh button click event handler.
        /// </summary>
        /// <param name="sender">The sender.</param>
        /// <param name="e">The <see cref="System.EventArgs"/> instance containing the event data.</param>
        protected void FeedsRefreshButtonClickEventHandler(object sender, EventArgs e)
        {
            ImageButton feedRefreshButton = sender as ImageButton;

            if (feedRefreshButton != null)
            {
                if (this.FeedRefreshing != null)
                {
                    string[] commandArguments =
                        feedRefreshButton.CommandArgument.Split(';');

                    // Check if the command argument is valid.

                    if (commandArguments.Length == 2)
                    {
                        string feedUrl = commandArguments[0];

                        int itemCount = 0;
                        int.TryParse(commandArguments[1], out itemCount);

                        this.FeedRefreshing(sender, new FeedRefreshEventArgs(feedUrl, itemCount));
                    }
                }
            }
        }

        /// <summary>
        /// Feedses the timer tick event handler.
        /// </summary>
        /// <param name="sender">The sender.</param>
        /// <param name="e">The <see cref="System.EventArgs"/> instance containing the event data.</param>
        protected void FeedsTimerTickEventHandler(object sender, EventArgs e)
        {
            this.MainLayoutMultiView.ActiveViewIndex = 1;
            this.AsynchronousLoadTimer.Enabled = false;
        }

        /// <summary>
        /// Feedses the show all button click event handler.
        /// </summary>
        /// <param name="sender">The sender.</param>
        /// <param name="e">The <see cref="System.EventArgs"/> instance containing the event data.</param>
        protected void FeedsShowAllButtonClickEventHandler(object sender, EventArgs e)
        {
            LinkButton feedShowAllLinkButton = sender as LinkButton;

            if (feedShowAllLinkButton != null)
            {
                if (this.FeedShowingAll != null)
                {
                    string feedUrl = feedShowAllLinkButton.CommandArgument;

                    this.FeedShowingAll(sender, new FeedRefreshEventArgs(feedUrl));
                }
            }
        }

        /// <summary>
        /// Raises the <see cref="E:System.Web.UI.Control.PreRender"/> event.
        /// </summary>
        /// <param name="e">An <see cref="T:System.EventArgs"/> object that contains the event data.</param>
        protected override void OnPreRender(EventArgs e)
        {
            base.OnPreRender(e);

            // TODO Remove this initialization from here.

            if (this.AsynchronousLoad == false)
            {
                this.MainLayoutMultiView.ActiveViewIndex = 1;
                this.AsynchronousLoadTimer.Enabled = false;
            }
        }

        #endregion

        #region Private Methods

        /// <summary>
        /// Initializes this instance.
        /// </summary>
        private void Initialize()
        {
            // Instantiate the model.

            IRSSAdvancedReaderModel model =
                new RSSAdvancedReaderModel();

            // Instantiate the presenter.

            this.presenter = new RSSAdvancedReaderPresenter(this, model);
        }

        /// <summary>
        /// Gets the feeds container.
        /// </summary>
        /// <returns>The active repeater.</returns>
        private Repeater GetFeedsContainer()
        {
            // Returns.

            return this.FeedsRepeater;
        }

        #endregion
    }
}